using System.Collections.Generic;
using System.Linq;

namespace unTroublemaker.Parsing
{
    internal class ParserVerifier
    {
        private readonly string _error;

        public ParserVerifier(List<ISpecificationParser> parsers)
        {
            var withInvalidTypename = parsers.Where(p => string.IsNullOrEmpty(p.ElementName)).ToList();
            if (withInvalidTypename.Any())
            {
                string concatenated = string.Join("\r\n", withInvalidTypename.Select(invalid => invalid.GetType().FullName));
                _error = "Following parsers did not specify element name: " + concatenated;
                return;
            }

            var duplicates = parsers.GroupBy(p => p.ElementName.ToLower()).Where(g => g.Count() > 1).ToList();
            if (duplicates.Any())
            {
                string concatenated = string.Join("\r\n",
                                                  duplicates.Select(
                                                      d =>
                                                      d.Key + ": " +
                                                      string.Join(", ", d.Select(p => p.GetType().FullName))));

                _error = "Multiple parsers cannot exist for same typename, please remove any of: \r\n" + concatenated;
            }
        }

        public bool HasErrors { get { return string.IsNullOrEmpty(_error) == false; } }

        public string Error { get { return _error; } }
    }
}